﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.DrawingCore;
using System.IO;
using System.Linq;
using System.Web;
using Company.Project.Infrastructure.Common;
using Company.Utility;
using Company.Utility.Encrypt;
using Company.Utility.ImageUpload;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Mvc;
using static System.IO.Directory;

namespace Company.Project.Web.ImageServices.Controllers
{
    public class ImageController : Controller
    {
        // GET: Image

        public ActionResult Upload()
        {
            var filePath = "";
            var iLimitFileSize = 0; //图片限定的大小        
            var limitFileType = new List<string>(); //限定的后缀名
            try
            {
                var request = Request.Form;
                var sign = request["sign"];
                var name = request["name"];
                if (string.IsNullOrEmpty(sign) || string.IsNullOrEmpty(name))
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名错误!\"}");
                }
                var date = DateTime.MinValue;
                DateTime.TryParse(request["date"], out date);
                if ((DateTime.Now - date).TotalMinutes > 5)
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名授权超时!\"}");
                }
                var key = ReadConfig.ReadAppSetting("ImageUploadKey");
                var md5 = MD5Helper.GetMd5(key + name+ date + key);
                if (sign != md5)
                {
                    return Content("{\"success\":false,\"filename\":\"\",\"message\":\"签名错误!\"}");
                }
                Response.ContentType = "text/plain";
                var arr = Convert.FromBase64String(request["UploadFile"]);
                var ms = new MemoryStream(arr);
                var bmp = new Bitmap(ms);
                //取出请求参数
                var sImgPath = ""; //原图路径
                var iWidth = 0; //图宽
                var iHeight = 0; //图高
                var sCutMode = "W"; //裁剪模式
                if (!string.IsNullOrEmpty(request["Path"]))
                {
                    //获取客户端传来的Path参数
                    var sPath = request["Path"];
                    sImgPath = $"{Directory.GetCurrentDirectory()}/UserFile/" + sPath + "/" + DateTime.Now.ToString("yyyyMM") + "/";
                }
                if (!string.IsNullOrEmpty(request["Width"]))
                {
                    //图宽
                    iWidth = TConvert.toInt32(request["Width"]);
                }
                if (!string.IsNullOrEmpty(request["Height"]))
                {
                    //图高
                    iHeight = TConvert.toInt32(request["Height"]);
                }
                if (!string.IsNullOrEmpty(request["CutMode"]))
                {
                    //获取客户端传来的Path参数
                    sCutMode = request["CutMode"];
                }
                var uploadPath = sImgPath;
                if (!Exists(uploadPath))
                {
                    CreateDirectory(uploadPath);
                }
                var sExtension = Path.GetExtension(name);
                var sFileName = DateTime.Now.ToString("ddHHmmssfff") + sExtension; //组装文件名
                if (sCutMode == "NoCut")
                {
                    bmp.Save(uploadPath + sFileName);
                    ms.Close();
                    return Content("{\"success\":true,\"filename\":\"" + "/UserFile/" + request["Path"] + "/" + DateTime.Now.ToString("yyyyMM") + "/" + sFileName + "\"}");
                }
                var access = new ImageServer_Access(iLimitFileSize, limitFileType, sImgPath, bmp,
                    iWidth, iHeight, sCutMode, name);
                if (access.SaveFile(ref filePath) != 1) return Content("{\"success\":false,\"filename\":\"\"}");
                ms.Close();
                return Content("{\"success\":true,\"filename\":\"" + "/UserFile/" + request["Path"] + "/" + DateTime.Now.ToString("yyyyMM") + "/" + filePath + "\"}");
            }
            catch (Exception e)
            {
                LoggerHelper.Log("图片上传异常:" + e.Message + ",详细错误:" + e.GetBaseException().Message);
            }
            return Content("{\"success\":false,\"filename\":\"\"}");
        }
    }
}